package com.fishingwithme.android.ui.viewmodels

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.fishingwithme.android.data.local.PreferencesManager
import com.fishingwithme.android.data.repository.FishingRepository
import com.google.gson.Gson
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import javax.inject.Inject
import kotlin.collections.emptyList

data class AuthUiState(
    val isLoading: Boolean = false,
    val isLoggedIn: Boolean = false,
    val username: String = "",
    val password: String = "",
    val isPrivacyPolicyChecked: Boolean = false,
    val isUserAgreementChecked: Boolean = false,
    val error: String? = null
)

@HiltViewModel
class AuthViewModel @Inject constructor(
    private val repository: FishingRepository,
    private val preferencesManager: PreferencesManager
) : ViewModel() {
    
    private val _uiState = MutableStateFlow(AuthUiState())
    val uiState: StateFlow<AuthUiState> = _uiState.asStateFlow()
    
    init {
        checkLoginStatus()
    }
    
    private fun checkLoginStatus() {
        viewModelScope.launch {
            combine(
                preferencesManager.getLoginUser(),
                preferencesManager.getAccessToken()
            ) { loginUser, token ->
                val hasUser = !loginUser.isNullOrEmpty()
                val hasToken = !token.isNullOrEmpty()
                hasUser && hasToken
            }.collect { isLoggedIn ->
                _uiState.update { it.copy(isLoggedIn = isLoggedIn) }
            }
        }
    }
    
    fun login(username: String, password: String) {
        if (username.isBlank() || password.isBlank()) {
            _uiState.update { it.copy(error = "用户名和密码不能为空") }
            return
        }
        
        viewModelScope.launch {
            _uiState.update { it.copy(isLoading = true, error = null) }
            
            try {
                // 调用实际的登录API
                val credentials = mapOf(
                    "username" to username,
                    "password" to password
                )
                
                val response = repository.apiService.login(credentials)
                
                // 修改条件判断逻辑，只检查response.isSuccessful
                if (response.isSuccessful) {
                    // 登录成功，处理响应数据
                    val body = response.body()
                    
                    if (body != null && body.status) { // status是布尔类型
                        val data = body.data
                        val userToken = data.token


                        // 保存用户数据和token
                        preferencesManager.saveLoginUser(data)
                        preferencesManager.saveAccessToken(userToken)

                        // 更新UI状态
                        _uiState.update {
                            it.copy(
                                isLoading = false,
                                isLoggedIn = true,
                                error = null
                            )
                        }
                    } else {
                        // 登录状态为false或body为空
                        val errorMsg = body?.msg ?: "登录失败：验证失败"
                        _uiState.update {
                            it.copy(
                                isLoading = false,
                                error = errorMsg
                            )
                        }
                    }
                } else {
                    // HTTP请求失败
                    val errorMsg = when (response.code()) {
                        401 -> "用户名或密码错误"
                        else -> response.errorBody()?.string() ?: "网络请求失败：${response.code()}"
                    }
                    _uiState.update {
                        it.copy(
                            isLoading = false,
                            error = errorMsg
                        )
                    }
                }
            } catch (e: Exception) {
                // 处理网络异常
                _uiState.update {
                    it.copy(
                        isLoading = false,
                        error = e.message ?: "登录失败：网络错误"
                    )
                }
            }
        }
    }
    
    fun login() {
        login(uiState.value.username, uiState.value.password)
    }
    
    fun logout() {
        viewModelScope.launch {
            preferencesManager.clearLoginUser()
            preferencesManager.clearAccessToken()
            _uiState.update { AuthUiState() }
        }
    }
    
    fun clearError() {
        _uiState.update { it.copy(error = null) }
    }
    
    fun setPrivacyPolicyChecked(checked: Boolean) {
        _uiState.update { it.copy(isPrivacyPolicyChecked = checked) }
    }
    
    fun setUserAgreementChecked(checked: Boolean) {
        _uiState.update { it.copy(isUserAgreementChecked = checked) }
    }
    
    fun setUsername(username: String) {
        _uiState.update { it.copy(username = username) }
    }
    
    fun setPassword(password: String) {
        _uiState.update { it.copy(password = password) }
    }
}